<?
/**
 * VoiceOne Settings/Extensions/Provisioning
 *
 * @package voiceone
 * @subpackage  settings_extensions
 */
  include ("../../../../../admin/config/cfg.php");
  global $cwlang;
  require_once("$absBasePath/lib/xajax/xajax.inc.php"); 
  
  //================ XAJAX ================
  function changeTemplate($id){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    //extract template info
    if($id==0) $script=" showhideAddress('1'); showhideExternal('1'); ";
    else{
    	$res=$asterisk->getProvTemplate($id);
    	if(is_array($res)){
    		$t=$res[0];
        $dhcp=$t["dhcp"];
        $local=$t["local"];
    	} 
      $script=" showhideAddress('".$dhcp."'); showhideExternal('".$local."'); ";
    }
    // Return the xajaxResponse object
    $objResponse->addScript($script);
    return $objResponse->getXML();  
  }
    
  function processFormData($formData){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    //extract form params
    $prov=$formData["prov"];
    $id=$prov["id"];
    $template=$prov["template"];
    $mac=strtoupper($prov["mac"]);
    $ip=$prov["ip"];
    $external_ip=$prov["external_ip"];
    $external_port=$prov["external_port"];
    $hostname=$prov["hostname"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">";
    //extract template info
  	$res=$asterisk->getProvTemplate($template);
  	if(is_array($res)){
  		$t=$res[0];
      $dhcp=$t["dhcp"];
      $local=$t["local"];
  	} 
    // Check Template
    $templateErr=false;
    if($template==0){ 
      //template must be not null
      $errOut[]=T_("Client must be linked to a template");
      $objResponse->addAssign("templateErr","innerHTML",$imgErr);
      $templateErr=true;
    }
    if($templateErr===false) $objResponse->addAssign("templateErr","innerHTML","");
    // Check MAC ((hex)&&(unique)&&(match patterns for selected phone)) 
    $macPatternArr="";
    $res=$asterisk->getProvTemplate($template);
    if((is_array($res))&&(is_array($res[0]))){
    	$phone_type=$res[0]["id_phone"];
      $res=$asterisk->getPhoneType($phone_type);
      if((is_array($res))&&(is_array($res[0]))){
      	$macPatternArr=split(",",$res[0]["mac"]);
      }
    }
    $macArr=array();
    $res=$asterisk->getProvClient(0);
    $maci = 0;
    if(is_array($res)){
      foreach($res as $p){
        if($p["id"]!=$id) {$macArr[]=$p["mac"]; $maci++;}
      }
    }
    $macErr=false;
    if($mac!=""){ 
      //mac must be hex
      for($i=0; $i<strlen($mac); $i++){ 
        $ch=ord($mac[$i]);
        if(!( (($ch>47)&&($ch<58))||(($ch>64)&&($ch<71))||(($ch>96)&&($ch<103)))){
          $errOut[]= T_("MAC allows only hexadecimal characters. Please change it");
          $objResponse->addAssign("macErr","innerHTML",$imgErr);
          $macErr=true;
          break;
        }
      }
      if($macErr===false){
        //mac must be 12 characters long
        if(strlen($mac)!=12){
          $errOut[]= T_("MAC must be 12 characters long");
          $objResponse->addAssign("macErr","innerHTML",$imgErr);
          $macErr=true;
        }
        //mac must match phone patterns
        else if((is_array($macPatternArr))&&(!in_array(substr($mac,0,8),$macPatternArr,true))){
          $errOut[]= T_("MAC is not a valid value for selected phone");
          $objResponse->addAssign("macErr","innerHTML",$imgErr);
          $macErr=true;
        }
        //mac must be unique
        else if(false){
          $errOut[]= T_("MAC must be unique".$maci." ");
          $objResponse->addAssign("macErr","innerHTML",$imgErr);
          $macErr=true;
        }
//	else if((is_array($macArr))&&(in_array($mac,$macArr))){
//          $errOut[]= T_("MAC must be unique");
//          $objResponse->addAssign("macErr","innerHTML",$imgErr);
//          $macErr=true;
//        }
	

      }  
    }
    /*
    else{
    	$errOut[]= T_("MAC can not be null");
      $objResponse->addAssign("macErr","innerHTML",$imgErr);
      $macErr=true;
    }
    */
    if($macErr===false) $objResponse->addAssign("macErr","innerHTML","");
    // Check local Address (not null) [if dhcp off] 
    $ipErr=false;
    if($dhcp==0){
    	if(trim($ip)==""){
      	$errOut[]= T_("Local IP can not bu null with dhcp off");
        $objResponse->addAssign("ipErr","innerHTML",$imgErr);
        $ipErr=true;
      }
    }
    if($ipErr===false) $objResponse->addAssign("ipErr","innerHTML","");
    // Check external IP (not null) [if local off] 
    $extipErr=false;
    if(($local==0)&&(trim($external_ip)=="")){
    	$errOut[]= T_("External IP can not bu null for remote clients");
      $objResponse->addAssign("extipErr","innerHTML",$imgErr);
      $extipErr=true;
    }
    if($extipErr===false) $objResponse->addAssign("extipErr","innerHTML","");
    // Check external IP (not null) [if local off] 
    $extportErr=false;
    if(($local==0)&&(trim($external_port)=="")){
    	$errOut[]= T_("External port can not bu null for remote clients");
      $objResponse->addAssign("extportErr","innerHTML",$imgErr);
      $extportErr=true;
    }
    if($extportErr===false) $objResponse->addAssign("extportErr","innerHTML","");
    // Process Form
    if(isset($errOut)){
      $error="<div class=\"AlertBad\"><ul>";
      foreach($errOut as $err) $error.="<li>".$err."</li>";
      $error.="</ul></div>";
      $objResponse->addAssign("alert","innerHTML",$error);
      $objResponse->addAssign("loading","innerHTML","");
    }else{
      $objResponse->addAssign("loading","innerHTML","");
      $script=" document.getElementById('mainform').submit(); ";
      $objResponse->addScript($script);
    }
    // Return the xajaxResponse object
    return $objResponse->getXML();  
  }
  $xajax = new xajax();
  $xajax->registerFunction("changeTemplate");
  $xajax->registerFunction("processFormData");
  $xajax->processRequests();

  //================ POST AND GET =================
  if((count($_POST)>0)&&(is_array($_POST["prov"]))){
    $provClient=$_POST["prov"];
    $entry=array(
        "id" => $provClient["id"],
        "id_client" => $provClient["id_client"],
        "id_template" => $provClient["template"],
        "mac" => strtoupper($provClient["mac"]),
        "ip" => $provClient["ip"],
        "external_ip" => $prov["external_ip"],
        "external_port" => $prov["external_port"],
        "hostname" => $prov["hostname"]
      );
    $ret=$asterisk->putProvClient($entry);
    if($ret>0) $alert="<div class=\"AlertGood\">".T_("Provisioning client has been saved")."</div>";
    else $alert="<div class=\"AlertBad\">".T_("Provisioning client hasn't been saved")."</div>";
    //go to main page
    goToMainPage($alert,"../");
  }
  //================= PAGE LOGIC ==================
  if((!isset($_GET["id"]))||(trim($_GET["id"])=="")) header("location: ../");
  //get provisioning client info
  $html="";
  $res=$asterisk->getProvClient($_GET["id"]);
  if(is_array($res)){
    $p=$res[0];
    $id=$p["id"];
    $id_client=$p["id_client"];
    $template=$p["id_template"];
    $mac=$p["mac"];
    $ip=$p["ip"];
    $external_ip=$p["external_ip"];
    $external_port=$p["external_port"];
    $hostname=$p["hostname"];
    //extension
    $clientArr=$asterisk->getClient($id_client,0);
    if(is_array($clientArr)){
      $client_name=$clientArr[0]["name"]." ".$clientArr[0]["surname"]." &lt;".$clientArr[0]["extension"]."&gt;";
    }
  }
  //get templates
  $templateOpt="";
  $res=$asterisk->getProvTemplate(0);
  if(is_array($res)){
    foreach($res as $t){
      if($t["id"]==$template) $selected="selected=\"selected\""; else $selected="";
      $res=$asterisk->getPhoneType($t["id_phone"]);
      if(is_array($res)){
      	$phone_name="(".$res[0]["vendor"].$res[0]["model"].")";
      }
      $templateOpt.="<option value=\"".$t["id"]."\" $selected>".$t["name"]." ".$phone_name."</option>";
    }
  }
  $templateOpt="<option value=\"0\" $selected>".T_("[none]")."</option>".$templateOpt;
  //extract template info
	$res=$asterisk->getProvTemplate($template);
	if(is_array($res)){
		$t=$res[0];
    $dhcp=$t["dhcp"];
    $local=$t["local"];
	} 
  //set dhcp radio
  if($dhcp==1){
  	$dhcp_on="checked=\"checked\"";
    $dhcp_off="";
    $disable_ip="disabled=\"disabled\"";
  }else{
  	$dhcp_on="";
    $dhcp_off="checked=\"checked\"";
    $disable_ip="";
  }
  //set local radio
  if($local==1){
  	$local_on="checked=\"checked\"";
    $local_off="";
    $display_external="display:none;";
  }else{
  	$local_on="";
    $local_off="checked=\"checked\"";
    $display_external="display:block;";
  }
  
  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../../../admin/lib/xajax/"); 
  ?>
    <?$nav="clients";include("../../navigation.php");?>
    <div class="SectionHeader">
      <h1><?=sprintf(T_("Edit Provisioning for %1\$s"),$client_name )?></h1>
      <h3><a href="../" class="admin" ><?=T_("Return without save")?></a></h3>
    </div>  
    <div id="alert"></div>
    <div id="basic_form">
      <form id="mainform" action="<?=$PHP_SELF?>" method="post">
        <!-- General Info -->
        <h2><?=T_("Client Information")?></h2>
        <p class="blockintro"><?=T_("Enter client's provisioning settings")?></p>
        <div class="block">
          <dl style="margin-bottom:0;padding-bottom:0">
            <dt class="required"><label for="prov[template]"><?=T_("Template")?>:</label></dt>
            <dd><select id="prov[template]" name="prov[template]" onchange="xajax_changeTemplate(this.options[this.selectedIndex].value);"><?=$templateOpt?></select> <span id="templateErr"></span></dd>
            <dt class="required"><label for="prov[mac]"><?=T_("MAC")?>:</label></dt>
            <dd><input type="text" maxlength="12" id="prov[mac]" name="prov[mac]" value="<?=$mac?>" /> <span id="macErr"></span></dd>
         	</dl>
        </div>
        <!-- Remote Network -->
        <h2><?=T_("Connection")?></h2>
        <p class="blockintro"><?=T_("Enter client's type of connection")?></p>
        <div class="block">
          <dl style="margin-top:0;padding-top:0">
          <dt class="required"><label for="prov[local]"><?=T_("Connection")?>:</label></dt>
            <dd>
              <input type="radio" id="local_on" name="prov[local]" value="1" disabled="disabled" <?=$local_on?> /><span style="vertical-align:bottom;"><?=T_("Local")?></span>&nbsp;
              <input type="radio" id="local_off" name="prov[local]" value="0" disabled="disabled" <?=$local_off?>/><span style="vertical-align:bottom;"><?=T_("Remote")?></span>  
            </dd>
          </dl>
          <dl style="margin-top:0;padding-top:0;<?=$display_external?>" id="external">  
            <dt class="required"><label for="prov[external_ip]"><?=T_("External Ip")?>:</label></dt>
            <dd><input type="text" id="prov[external_ip]" name="prov[external_ip]" value="<?=$external_ip?>" /><span id="extipErr"></span></dd>
            <dt class="required"><label for="prov[external_port]"><?=T_("External Port")?>:</label></dt>
            <dd><input type="text" id="prov[external_port]" name="prov[external_port]" value="<?=$external_port?>" /><span id="extportErr"></span></dd>
          </dl>
        </div>
  			<!-- Local Network -->
        <h2><?=T_("Local Network")?></h2>
        <p class="blockintro"><?=T_("Enter client's local network settings")?></p>
        <div class="block">
          <dl style="margin-bottom:0;padding-bottom:0">
            <dt class="required"><label for="prov[dhcp]"><?=T_("DHCP")?>:</label></dt>
            <dd>
              <input type="radio" id="dhcp_on" name="prov[dhcp]" value="1" disabled="disabled" <?=$dhcp_on?> /><span style="vertical-align:bottom;"><?=T_("On")?></span>&nbsp;
              <input type="radio" id="dhcp_off" name="prov[dhcp]" value="0" disabled="disabled" <?=$dhcp_off?> /><span style="vertical-align:bottom;"><?=T_("Off")?></span>  
            </dd>
          </dl>
          <dl style="margin-top:0;padding-top:0;<?=$local_display?>" id="dhcp">
            <dt class="required"><label for="prov[ip]"><?=T_("IP")?>:</label></dt>
            <dd><input type="text" maxlength="15" id="prov[ip]" name="prov[ip]" value="<?=$ip?>" <?=$disable_ip?>/><span id="ipErr"></span></dd>
            <dt class="required"><label for="prov[hostname]"><?=T_("Hostname")?>:</label></dt>
            <dd><input type="text" id="prov[hostname]" name="prov[hostname]" value="<?=$hostname?>" <?=$disable_ip?>/><span id="hostnameErr"></span></dd>
          </dl>
        </div>
        <!-- Action Buttons -->
        <div class="action">
          <input type="hidden" id="prov[id]" name="prov[id]" value="<?=$id?>" />
          <input type="hidden" id="prov[id_client]" name="prov[id_client]" value="<?=$id_client?>" />
          <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/></a>
          <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick=" document.getElementById('alert').innerHTML=''; xajax_processFormData(xajax.getFormValues('mainform')); "/></a>
        </div>
      </form>
    </div>      
    
    <script>
    	function showhideAddress(value){
        if(value==1){
        	document.getElementById('dhcp_off').checked='';
          document.getElementById('dhcp_on').checked='checked';
          document.getElementById('prov[ip]').value='<?=$ip?>';document.getElementById('prov[ip]').disabled='disabled';
          document.getElementById('prov[hostname]').value='<?=$hostname?>';document.getElementById('prov[hostname]').disabled='disabled';
        }else{
          document.getElementById('dhcp_on').checked='';
          document.getElementById('dhcp_off').checked='checked';
          document.getElementById('prov[ip]').value='<?=$ip?>';document.getElementById('prov[ip]').disabled='';
          document.getElementById('prov[hostname]').value='<?=$hostname?>';document.getElementById('prov[hostname]').disabled='';
        }
      }
      function showhideExternal(value){
        if(value==1){
        	document.getElementById('local_off').checked='';
          document.getElementById('local_on').checked='checked';
          document.getElementById('external').style.display='none';
          document.getElementById('prov[external_ip]').value='';
          document.getElementById('prov[external_port]').value=''; 
        }else{
        	document.getElementById('local_on').checked='';
        	document.getElementById('local_off').checked='checked';
          document.getElementById('external').style.display='block';
          document.getElementById('prov[external_ip]').value='<?=$external_ip?>';
          document.getElementById('prov[external_port]').value='<?=$external_port?>';
        }
      }
    </script>
  <?
  $contents=ob_get_contents();
  ob_end_clean();
  
  //================ SIDEBAR ================
  ob_start(); 
  ?>
    <div class="Sidebar">
      <?$sel="provisioning";include("../../../sidebar.php");?>
      <h1><?=T_("Informations")?></h1>
    </div>
  <?  
  $sidebar=ob_get_contents();
  ob_end_clean();
  
  //================ SETTINGS ================
  $smarty->assign("section", "extensions");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->display('settings.tpl');
?>